/**
 * All Rights Reserved , Copyright (C) 2021 , 青岛鼎信通讯股份有限公司
 *
 *MpmProjectSuperviseController
 * 项目督办
 *
 * 修改纪录
 * 2021-07-28 版本：1.0 wudaliang 创建。
 * @version 版本：1.0
 * @author 作者：wudaliang
 * 创建日期：2021-07-28
 */

package com.topscomm.mpm.controller;

import com.topscomm.basic.exception.BusinessException;
import com.topscomm.basic.exception.ServiceException;
import com.topscomm.basic.exception.BusinessException;
import com.topscomm.cbo.pojo.CboApprovalNodeInsEntity;
import com.topscomm.cbo.pojo.CboExcelImportConfigEntity;
import com.topscomm.cbo.service.ICboMessageAppService;
import com.topscomm.cbo.service.impl.CboApprovalNodeInsService;
import com.topscomm.cbo.service.impl.CboApprovalNodeService;

import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;

import com.topscomm.cbo.service.impl.CboExcelImportConfigService;
import com.topscomm.mpm.pojo.MpmProjectEntity;
import com.topscomm.mpm.pojo.MpmProjectSuperviseEntity;
import com.topscomm.mpm.script.MpmProjectSuperviseScript;
import com.topscomm.mpm.service.impl.MpmProjectService;
import com.topscomm.mpm.service.impl.MpmProjectSuperviseService;
import com.topscomm.pub.util.*;
import com.topscomm.tap.TapService;
import com.topscomm.pub.vo.Page;
import com.topscomm.pub.vo.Query;
import org.apache.commons.collections4.Put;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import com.topscomm.basic.util.SQLAdapter;
import com.topscomm.mpm.controller.auto.MpmProjectSuperviseControllerAuto;
import com.topscomm.pub.vo.ResponseResult;
import com.topscomm.tap.common.TapSystemConst.TapOperationTypeEnum;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author: wudaliang
 * @date: 2021-07-28
 * @description:项目督办Controller
 * @modify:
 */
@RestController
@RequestMapping("mpm/projectSupervise")
public class MpmProjectSuperviseController extends MpmProjectSuperviseControllerAuto implements IMpmProjectSuperviseController {

	@Autowired
	private CboApprovalNodeInsService cboApprovalNodeInsService;
	@Autowired
	private ICboMessageAppService cboMessageAppService;
	@Autowired
	private MpmProjectSuperviseService mpmProjectSuperviseService;

	/**
	 * @author: wudaliang
	 * @date: 2021-07-28
	 * @param paraMap
	 * @return
	 * @description:转换出查询SQL语句
	 * @modify:
	 */
	@Override
	protected String spellListSql(Map<String, Object> paraMap) {
		StringBufferProxy sql = new StringBufferProxy();
		sql.appendSingle(" enabled=1 ");
		if (paraMap.containsKey("qry_state")) {
			String value = paraMap.get("qry_state").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and state={0}", value);
		}
		if (paraMap.containsKey("qry_supervisename")) {
			String value = paraMap.get("qry_supervisename").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and supervisename like  '%{0}%' ", value);
		}
		if (paraMap.containsKey("qry_projectcode")) {
			String value = paraMap.get("qry_projectcode").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and projectcode =  '{0}' ", value);
		}
		if (paraMap.containsKey("qry_superviseobjecttype")) {
			String value = paraMap.get("qry_superviseobjecttype").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and {0} like {1} ", SQLAdapter.concat(new String[] { "','", MpmProjectSuperviseEntity.FieldSuperviseobjecttype, "','" }),
						SQLAdapter.concat(new String[] { "'%,'", value, "'%,'" }));
		}
		if (paraMap.containsKey("qry_milepostcode")) {
			String value = paraMap.get("qry_milepostcode").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and superviseobjectcode = '{0}' ", value);
		}
		if (paraMap.containsKey("qry_docno")) {
			String value = paraMap.get("qry_docno").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and docno like '%{0}%'", value);
		}
		if (paraMap.containsKey("qry_begindocdate")) {
			String value = paraMap.get("qry_begindocdate").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and docdate >= {0} ", SQLAdapter.toDateLong(value + " 00:00:00"));
		}
		if (paraMap.containsKey("qry_enddocdate")) {
			String value = paraMap.get("qry_enddocdate").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and docdate <= {0}", SQLAdapter.toDateLong(value + " 23:59:59"));
		}
		if (paraMap.containsKey("qry_deptname")) {
			String value = paraMap.get("qry_deptname").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and (deptid in ( SELECT id from CboDept where fullname like '%{0}%'))", value);
		}
		if (paraMap.containsKey("qry_username")) {
			String value = paraMap.get("qry_username").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and (username like '%{0}%')", value);
		}
		if (paraMap.containsKey("qry_deptcode")) {
			String value = paraMap.get("qry_deptcode").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and deptcode like '{0}%'", value);
		}
		if (paraMap.containsKey("qry_where")) {
			String value = paraMap.get("qry_where").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and {0}", value);
		}
		if (this.getUserBean().getUser().getAdminlevel() < 1)// 管理员、超级管理员，不控制权限
		{
			String dataPession = service.getDataPermission(TapOperationTypeEnum.Select, "", this.getUserBean());
			if (StringUtil.isEmpty(dataPession))// 默认权限只能看本人，部门负责人为自己的部门和下级部门的数据
			{
//				String deptcodes_header = ConvertUtil.convertToString(this.getUserBean().getUser().getValue("deptcodes_header"));
//				if (StringUtil.isEmpty(deptcodes_header))
//					sql.appendSingle(" and (usercode = '{0}' or deptcode ='{1}' or deptcode = '{2}' )", this.getUserBean().getUser().getCode(), this.getUserBean().getDept().getCode(), this
//							.getUserBean().getWorkDept().getCode());
//				else
//					sql.appendSingle(" and (deptcode in ({0})  or usercode = '{1}' or deptcode ='{2}' or deptcode = '{3}' )", deptcodes_header, this.getUserBean().getUser().getCode(), this
//							.getUserBean().getDept().getCode(), this.getUserBean().getWorkDept().getCode());
			} else// 使用数据权限
			{
				sql.appendSingle(" and {0} ", dataPession);
			}
		}
		return sql.toString();
	}

	/**
	 * @author: wudaliang
	 * @date: 2021-07-28
	 * @param paraMap
	 * @return
	 * @description:转换出查询SQL语句
	 * @modify:
	 */
	@Override
	@GetMapping(value = "/refList")
	public ResponseResult<Object> refList(@RequestParam(required = false) Map<String, Object> paraMap) {
		return super.refList(paraMap);
	}

	/**
	 *
	 * @description: 提交审批前
	 * @param dataMap
	 * @param paraMap
	 * @throws Exception
	 * @author: wudaliang
	 * @date: 2021-07-28
	 * @modify:
	 */
	@Override
	protected void beforeSubmit(Map<String, Object> dataMap, Map<String, Object> paraMap) throws Exception {
		super.beforeSubmit(dataMap, paraMap);
		StringBufferProxy mailtitle = new StringBufferProxy();
		mailtitle.appendSingle("{0}{1}于{2}提交项目督办申请,单据编号{3}! ", dataMap.get("dispdeptcode"), dataMap.get("username"), DateUtil.dateToString(new Date(), "yyyy-MM-dd"), dataMap.get("docno"));
		dataMap.put("maintitle", mailtitle.toString());
	}

	/**
	 * 导入excel处理历史数据
	 *
	 * @description:
	 * @param excelFile
	 * @param paraMap
	 * @return
	 * @author:
	 * @date:
	 * @modify:
	 */
	@PostMapping(value = "/handlehistorydata")
	public ResponseResult<Object> importExcel(@RequestParam("file") MultipartFile excelFile,
											  @RequestParam(required = false) Map<String, Object> paraMap) {
		// 得到文件流
		File file = FileUtil.multipartFileToFile(excelFile);
		try {
			int records = this.mpmProjectSuperviseService.executeImportExcel(paraMap, file);
			return ResponseResult.ok("成功导入" + records + "条数据");
		} catch (Exception ex) {
			throw new BusinessException(ex.getMessage(), true);
		}
	}

	// 该接口没被使用
//	@GetMapping("/getApprovalCount")
//	public ResponseResult<Object> getApprovalCount(@RequestParam(required = false) Map<String, Object> paraMap){
//		StringBufferProxy sql = new StringBufferProxy();
//		sql.appendSingle(" APPROVALUSERID ='{0}' AND STATE=1 and SOURCETYPE='MpmProjectSupervise' ",this.getUserBean().getUser().getId());
//		List<CboApprovalNodeInsEntity> cboApprovalNodeInsEntities = cboApprovalNodeInsService
//			.queryByWhere(sql.toString());
//		HashMap<String, Object> map = new HashMap<>();
//		if(cboApprovalNodeInsEntities.size()>0){
//			map.put("exitsApproval",true);
//			return ResponseResult.ok(map);
//		}else{
//			map.put("exitsApproval",false);
//			return ResponseResult.ok(map);
//		}
//	}

	/**
	 *
	 * @description: 重写datacodelist
	 * @param paraMap
	 * @throws Exception
	 * @author: houyuhang
	 * @date: 2021-09-06
	 * @modify:
	 */
	@Override
	@GetMapping(value = "/dataCodeList")
	public ResponseResult<Object> dataCodeList(@RequestParam(required = false) Map<String, Object> paraMap) {
		ResponseResult<Object> responseResult = super.dataCodeList(paraMap);
		Map<String,Object> codeMap  = (Map<String, Object>) responseResult.getResult();
		List<Map<String, Object>> superviseobjectList = datacodeCache.getCodeListMap("MpmSuperviseObject", "", "sortcode");
		codeMap.put("superviseobjectList", superviseobjectList);
		List<Map<String, Object>> supervisetypeList = datacodeCache.getCodeListMap("MpmSuperviseType", "", "sortcode");
		codeMap.put("supervisetypeList", supervisetypeList);
		List<Map<String, Object>> meettypeList = datacodeCache.getCodeListMap("MpmMeetType", "", "sortcode");
		codeMap.put("meettypeList", meettypeList);
		List<Map<String, Object>> superviseendstateList = datacodeCache.getCodeListMap("MpmSuperviseEndState", "", "sortcode");
		codeMap.put("superviseendstateList", superviseendstateList);
		List<Map<String, Object>> bidsourcetypeList = datacodeCache.getCodeListMap("MpmSelfBidScoreType", "", "sortcode");
		codeMap.put("bidsourcetypeList", bidsourcetypeList);
		List<Map<String, Object>> superviseobjecttypeList = datacodeCache.getCodeListMap("MpmSuperviseObjectType", "", "sortcode");
		codeMap.put("superviseobjecttypeList", superviseobjecttypeList);
		// 部门表
		List<Map<String, Object>> deptCommonCodeList = datacodeCache.getCodeListMap("DeptCommonCodeTrack", "", "sortcode");
		codeMap.put("deptCommonCodeList", deptCommonCodeList);
		// 项目等级
		List<Map<String, Object>> projectlevelList = datacodeCache.getCodeListMap("MpmProjectLevel", "", "sortcode");
		codeMap.put("projectlevelList", projectlevelList);
		return ResponseResult.ok(codeMap);
	}

	@Override
	protected void afterSubmit(Map<String, Object> dataMap, Map<String, Object> paraMap) throws Exception {
		super.afterSubmit(dataMap, paraMap);
		this.service.sendAppMessageToCcStaff(paraMap);
	}
	/***
	 * @description: 项目立项变更
	 * @param paraMap
	 * @return
	 * @author: houyuhang
	 * @date:
	 **/
	@PutMapping(value = "/updateSuperviseUser")
	public ResponseResult<Object> updateSuperviseUser(@RequestBody(required = false) Map<String, Object> paraMap) {
		try {
			mpmProjectSuperviseService.updateSuperviseUser(paraMap);
			return ResponseResult.ok("更新成功");
		} catch (Exception ex) {
			return handleControllerException(ex);
		}
	}


	/**
	 * @Description:    督办审核单明细报表数据
	 * @Author:         wuyuyang
	 * @Return:         com.topscomm.pub.vo.ResponseResult<java.lang.Object>
	 * @exception:
	 * @Date:           15/3/2023 下午5:40
	 * @Version:        1.0
	 **/
	@PostMapping(value = "/dataWithSupervisionDatailForm")
	public ResponseResult<Object> dataWithSupervisionDatailForm(@RequestBody(required = false) Map<String, Object> paraMap) {
		// 安全解码
		BaseUtil.decodeSecureMap(paraMap);
		Query query = new Query(paraMap);
		//处理字符串数组参数
		paraMap.forEach((key,value)->{
			if(value instanceof List){
				paraMap.replace(key,  ((List<String> )value).stream().map(s->"'"+s+"'").collect(Collectors.joining(",")));
			}
		});
		String sqlWhere = this.service.spellListNewSql(paraMap);
		paraMap.put("whereSql", sqlWhere);
		int totalCount = this.service.getCount1(paraMap,"getCountForSupervise");
		List<Map<String, Object>> tempList = null;
		tempList = this.service.queryMapForPage(sqlWhere, query.getCurrentPage(), query.getPageSize(),
					query.getSidx(), query.getSord(),"getSupervisionDatailForm");
		// 处理显示值
		this.service.setDispFields(tempList);
		// 对数据进行处理
		List<Map<String, Object>> list = this.service.dealtWithData(tempList);
		Page page = new Page(list, totalCount, query.getPageSize(), query.getCurrentPage());
		return ResponseResult.ok(page);
	}


	/**
	 * @Description:    导出excel
	 * @Author:         wuyuyang
	 * @Return:         com.topscomm.pub.vo.ResponseResult<java.lang.Object>
	 * @exception:
	 * @Date:           21/3/2023 下午9:13
	 * @Version:        1.0
	 **/
	@PostMapping(value = "/exportExcelForSupervise")
	public void exportExcel(@RequestBody(required = false) Map<String, Object> paraMap, HttpServletRequest request,
							HttpServletResponse response) {
		// 安全解码
		paraMap = BaseUtil.decodeSecureMap(paraMap);
		//处理字符串数组参数
		Set keyset = paraMap.keySet();
		for(Object key : keyset){
			if(paraMap.get(key) instanceof List){
				paraMap.replace(key.toString(),  ((List<String> )paraMap.get(key)).stream().map(s->"'"+s+"'").collect(Collectors.joining(",")));
			}
		}
		try {
			String sidx = ConvertUtil.convertToString(paraMap.get("sidx"));
			String sord = ConvertUtil.convertToString(paraMap.get("sord"));
			String cols = ConvertUtil.convertToString(paraMap.get("cols"));
			String sqlWhere = this.service.spellListNewSql(paraMap);
			StringBufferProxy sql = new StringBufferProxy();
			if (!StringUtil.isEmpty(sidx) && !StringUtil.isEmpty(sord)) {
				sql.appendSingle(" order by {0} {1} ", sidx, sord);
				sqlWhere = sqlWhere + sql.toString();
			}
			List<Map<String, Object>> tempList = this.service.queryMapByWhere(sqlWhere, "getCountForSupervise");
			// 显示值
			tempList.stream().forEach(m ->{
				this.service.setDispFields(m,datacodeCache);
			});
			// 对数据进行处理
			List<Map<String, Object>> list = this.service.dealtWithData(tempList);
			int i = 1;
			// 序号
			for(Map<String, Object> map : list){
				map.put("index", ConvertUtil.convertToString(i));
				i++;
			}
			String[] colArray = cols.split(",");
			InputStream inStream = OfficeOperateUtil.exportExeclXlsx(list, colArray);
			String fileName = "导出数据.xlsx";
			response.setContentType("application/octet-stream");
			response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
			response.setHeader("FileName", URLEncoder.encode(fileName, "utf-8"));
			response.setHeader("Access-Control-Expose-Headers", "FileName");
			OutputStream outStream = response.getOutputStream();
			byte[] bytes = new byte[2048];
			int len;
			while ((len = inStream.read(bytes)) != -1) {
				outStream.write(bytes, 0, len);
			}
			inStream.close();
		} catch (Exception ex) {
			throw new BusinessException(ex.getMessage(), true);
		}
	}




}

